import * as vscode from 'vscode';
import log from "./logger";
import {URI} from "./config";
import request = require("request-promise");

export function activate(context: vscode.ExtensionContext) {
    log("endPointUrl:"+JSON.stringify(URI));
	let colorTheme = vscode.workspace.getConfiguration('workbench').get('colorTheme');
    const myViewProvider = new MyViewProvider(context.extensionUri, colorTheme as string);
    context.subscriptions.push(vscode.window.registerWebviewViewProvider('aiXcoder formula2code', myViewProvider));
    context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(event => {
        if (event.affectsConfiguration('workbench.colorTheme')) {
            let colorTheme = vscode.workspace.getConfiguration('workbench').get('colorTheme');
            myViewProvider.postMessage({ 'colorTheme': colorTheme });
        }
    }));
}

async function getCode(pseudo: any) {
    let options={
        method: 'POST',
        uri: vscode.workspace.getConfiguration().get("aiXcoder.endPointUrl") + '/get_code',
        body: pseudo,
        json: true,
        timeout: 5000
    }; 
    let res=await request(options);
    return res; 
} 
export function deactivate() {}

class MyViewProvider implements vscode.WebviewViewProvider {
    private _view?: vscode.WebviewView;
    private defaultTheme: string;

    constructor(private readonly _extensionUri: vscode.Uri, theme: string) {
        this.defaultTheme = theme.indexOf("Dark") != -1 ? "white" : 'black';
    }

    resolveWebviewView(webviewView: vscode.WebviewView) {
        this._view = webviewView;
        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [this._extensionUri]
        };
        webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);
    
        webviewView.webview.onDidReceiveMessage(msg => {
            log(JSON.stringify(msg));
            getCode(msg).then(data => {
                let editor = vscode.window.activeTextEditor;
                if (editor?.document.languageId == "cpp") {
                    let fullRange = new vscode.Range(
                        editor.document.positionAt(0),
                        editor.document.positionAt(editor.document.getText().length)
                    );
                    editor.insertSnippet(new vscode.SnippetString(data),fullRange);
                }else {
                    //打开一个新的编辑器
                    vscode.workspace.openTextDocument({language:"cpp",content:data}).then((doc)=>{
                        vscode.window.showTextDocument(doc);
                    });
                }
            }); 
        });
        //监听切换主题
        this._view.onDidChangeVisibility(() => {
            let colorTheme = vscode.workspace.getConfiguration('workbench').get('colorTheme');
            log("colorTheme:" + colorTheme);
            this._view?.webview.postMessage({ 'colorTheme': colorTheme });
        });
    }
    public postMessage(message: any) {
        this._view?.webview.postMessage(message);
    }

    private _getHtmlForWebview(webview: vscode.Webview): string {
        const blackUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'images', 'login-black.png'));
        const whiteUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'images', 'login-white.png'));
        const stylecss=webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media','css','style.css'));
        const indexjs=webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media','js','index.js'));
        const formulaEditorjs=webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media','js','formula-editor.min.js'));
        const myformulaEditorjs=webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media','js','myformula-editor.js'));
        const jqueryminjs=webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media','js','jquery.min.js'));
        
        return `   
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8" />
            <link rel="icon" href="./favicon.ico" />
            <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width" />
            <title>aiXcoder h5</title>
            <link href="${stylecss}" rel="stylesheet">
            <link href="${webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media','css','main.css'))}" rel="stylesheet">
            <style>
                .title i{
                    width: 110px;
                    height: 23px;
                    display: block;
                    background: url('${whiteUri}') no-repeat;
                    background-size: 100%;   
                }
                .black .title i{
                    background: url('${blackUri}') no-repeat;
                    background-size: 100%;   
                }
            </style>
        </head>
        <body class="${this.defaultTheme}">
            <div class="title">
                <i></i>
                <span>Formula2Code</span>
            </div>
            <div id="page">
                <h5 class="">数据字典<span>*</span></h5>
                <div id="editor—wrapper">
                    <div id="toolbar-container"></div>
                    <div id="editor-container"></div>
                </div>
                <!-- <textarea class="m-b-30" placeholder="请输入JSON格式" id="dict"></textarea> -->
                <h5>计算公式<span>*</span></h5>
                <textarea id="pseudoCode" placeholder="请输入伪代码"></textarea>
                <div id="ckeditor"></div>
                <button id="c-button" onclick="generate()">生成C语言代码</button>
            </div>
            <script src="${jqueryminjs}"></script>
            <script src="${indexjs}"></script>
            <!--<script src="${formulaEditorjs}"></script>
            <script src="${myformulaEditorjs}"></script>-->
            <script type="text/javascript" src="${webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'js'))}/ckeditor.js"></script>
            <script type="text/javascript" src="${webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'js'))}/main.js"></script>
        </body>
        </html>
        `;
    }
}